package com.fast.cron.common.server;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.MapUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * the utils of http
 *
 * @author: Leo Jie
 * @date: 2018-10-07 21:21
 * @version: v1.0
 */
public class HttpRequestsUtils {
    public static boolean hasParam(final HttpServletRequest request, String param) {
        return request.getParameter(param) != null;
    }


    public static String getParam(final HttpServletRequest request, String name) throws ServletException {
        final String p = request.getParameter(name);
        if (null == p) {
            throw new ServletException("messing required param '" + name + "'");
        } else {
            return p;
        }
    }

    public static String getParam(final HttpServletRequest request, final String name,
                                  final String defaultVal) {
        final String p = request.getParameter(name);
        if (p == null) {
            return defaultVal;
        }
        return p;
    }

    public static int getIntParam(final HttpServletRequest request, final String name)
            throws ServletException {
        final String p = getParam(request, name);
        return Integer.parseInt(p);
    }

    public static int getIntParam(final HttpServletRequest request, final String name,
                                  final int defaultVal) {
        if (hasParam(request, name)) {
            try {
                return getIntParam(request, name);
            } catch (final Exception e) {
                return defaultVal;
            }
        }

        return defaultVal;
    }

    public static Map<String, String> getBodyFromRequest(HttpServletRequest request) {
        Map<String, String> bodyMap = null;
        try {
            BufferedReader br = request.getReader();
            String str;
            StringBuilder wholeStr = new StringBuilder();
            while ((str = br.readLine()) != null) {
                wholeStr.append(str);
            }
            //noinspection unchecked
            bodyMap = (Map<String, String>) JSON.parse(wholeStr.toString());
        } catch (IOException io) {
            io.printStackTrace();
        }
        if (MapUtils.isEmpty(bodyMap)) {
            bodyMap = new HashMap<>(1);
            bodyMap.put("api_author", "leo");
        }
        return bodyMap;
    }

}  